package net.tngou.iask.action.api;

import java.sql.Timestamp;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import net.tngou.iask.action.BaseAction;
import net.tngou.iask.pojo.At;
import net.tngou.iask.pojo.Msgs;
import net.tngou.iask.service.MsgsService;
import net.tngou.iask.util.Freemarker;

/**
 * 消息列表
 * @author tngou@tngou.net
 *
 */
public class MsgsApi extends BaseAction {

	
	/**
	 * 未读消息
	 */
	public void list() {
		if(user==null){
			run_nologin();return;
		}
		MsgsService service = new MsgsService();
		List<Map<String, Object>> list = service.getList(user.getId());	
		JSONArray array = new JSONArray();
		list.forEach(e->{
			JSONObject json=(JSONObject) JSON.toJSON(e);
			json.put("time", new Freemarker().prettytime((Timestamp) e.get("time")));
			array.add(json);
		});
		printJson(toJsonP(array));
	}
	
	/**
	 * 未读At功能
	 */
	@SuppressWarnings("unchecked")
	public void atlist() {
		if(user==null){
			run_nologin();return;
		}
		List<At> list = (List<At>) service.getList("user="+user.getId()+" AND isread=0", At.class);
		JSONArray array = new JSONArray();
		list.forEach(e->{
			JSONObject json=(JSONObject) JSON.toJSON(e);
			json.put("time", new Freemarker().prettytime(e.getTime()));
			array.add(json);
		});
		printJson(toJsonP(array));
	}
	
	/**
	 * 未读系统消息
	 */
	@SuppressWarnings("unchecked")
	public void syslist() {
		if(user==null){
			run_nologin();return;
		}
		List< Msgs> list = (List<Msgs>) service.getList("user="+user.getId()+" AND type=1 AND  isread=0", Msgs.class);
		JSONArray array = new JSONArray();
		list.forEach(e->{
			JSONObject json=(JSONObject) JSON.toJSON(e);
			json.put("time", new Freemarker().prettytime(e.getTime()));
			array.add(json);
		});
		printJson(toJsonP(array));
	}
	
	
	/**
	 * 发送私信
	 */
	public void send() {
		if(user==null){
			run_nologin();return;
		}
		Msgs bean= getAsk(Msgs.class);
		if(bean.getFriend()==0||isEmpty(bean.getMsg()))
		{
			run_false("请求的参数不正确！");return;
		}
		bean.setUser(user.getId());
		bean.setIsread(1);//设置可读
		bean.setSender(user.getId());
		bean.setReceiver(bean.getFriend());
		bean.setType(0);
		long id = bean.save();//保存发送
		if(id>0)
		{
			bean.setId(0);
			bean.setUser(bean.getFriend());
			bean.setIsread(0);//设置可读
			bean.save();//保存用户一份
			run_success("发送成功！");return;
		}else
		{
			run_false("发送失败！");return;
		}
	}
	
	/**
	 * 删除私信
	 */
	public void delete() {
		if(user==null){
			run_nologin();return;
		}
		if(ask.getId()==0)
		{
			run_false("请求的参数不正确！");return;
		}
		Msgs msgs = new Msgs().get(ask.getId());
		if(msgs==null||msgs.getUser()!=user.getId())
		{
			run_false("请求的数据不正确！");return;
		}
		boolean b = msgs.delete();
		if(b)
		{
			run_success("删除成功！");return;
		}else
		{
			run_false("删除失败！");return;
		}
	}
}
